from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from xml.dom.minidom import parse, parseString

from models.project import MasterControlProject, MasterControlSubProject

import logging

from settings import *
from utilities import *

class AvailableStoriesHandler(webapp.RequestHandler):
    def get(self, mcp_code):
        mcp = MasterControlProject.get_by_key_name(mcp_code)
        if not mcp:
            return
        current = GetIteration(mcp.pivotal_project_id, 'current', mcp.token)
        backlog = GetIteration(mcp.pivotal_project_id, 'backlog', mcp.token)
        stories = parseString('<external_stories />').documentElement
        count = 0
        for story in current.getElementsByTagName('story') + backlog.getElementsByTagName('story'):
            RemoveTags(story, 'project_id', 'url') #, 'created_at', 'accepted_at', 'uploaded_at')
            owner = story.getElementsByTagName('owned_by')
            if (owner and owner[0].firstChild and owner[0].firstChild.data):
                continue
            story.tagName = 'external_story'
            for id_tag in story.getElementsByTagName('id'):
                id_tag.tagName = 'external_id'
            stories.appendChild(story)
            count += 1
        stories.setAttribute('count', str(count))
        stories.setAttribute('total', str(count))
        stories.setAttribute('type', 'array')
        
        self.response.out.write(stories.toxml())
